# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Utility functions for the utility module"""

import json


def load_prompt_template(filepath: str) -> str:
  """Loads a prompt template from a file."""
  with open(filepath, "rt", encoding="utf-8") as f:
    return f.read()


def load_text_file(file_path):
  """Loads a text file."""
  try:
    with open(file_path, "rt", encoding="utf-8") as f:
      return f.read()
  except FileNotFoundError:
    print(f"Error: Text file not found at {file_path}")
    return None


def load_json(file_path):
  """Loads a JSON file."""
  try:
    with open(file_path, "rt", encoding="utf-8") as f:
      return json.load(f)
  except FileNotFoundError:
    print(f"Error: JSON file not found at {file_path}")
    return None
  except json.JSONDecodeError:
    print(f"Error: Could not decode JSON from {file_path}")
    return None


def assemble_script(target_model, param_mapping_code, hook_fn_code, shape_mapping_code):
  """Assembles the final Python script from generated parts."""
  # This is the system instruction template provided in the request.
  # We will fill it with the generated code.
  script_template = f"""# This file was auto-generated by a prompt chaining process.

\"\"\"
Conversion functions for '{target_model}' between MaxText and Hugging Face formats.

This script provides the necessary mappings and transformation functions (hooks)
to convert model parameters from a MaxText checkpoint to a Hugging Face
compatible format, and vice-versa.
\"\"\"


{param_mapping_code}

{hook_fn_code}

{shape_mapping_code}

"""
  return script_template
